package com.zjx.reggie.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.zjx.reggie.common.BaseContext;
import com.zjx.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String[] path = {
                "/employee/login",
                "/employee/logout",
                "/front/**" ,
                "/backend/**",
                "/common/**",
                "/user/login",
        };
        /*


        "
        *
        * */
        //  /**可以多级目录    /*只能一级目录
        //判断当前请求是否是要过滤的
        boolean flag = check(path, requestURI);
        if (flag) {
            filterChain.doFilter(request, response);
            return;
        }
        //判断是否登录
        String userId =(String) request.getSession().getAttribute("userId");
        if( userId != null){
            BaseContext.setId(userId);
            filterChain.doFilter(request,response);
            BaseContext.removeId();
            return;
        }

        String empId =(String) request.getSession().getAttribute("employee");
        if ( empId != null) {
            BaseContext.setId(empId);
            filterChain.doFilter(request, response);
            BaseContext.removeId();
            return;
        }

        //判断是否是异步请求
        if (isAjaxRequest(request)) {
            R<Object> notlog = R.error("NOTLOGIN");
            String s = JSONObject.toJSONString(notlog);
            servletResponse.getWriter().write(s);
        } else {
            response.sendRedirect(request.getContextPath() + "/backend/page/login/login.html");
        }
    }
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String accept = request.getHeader("accept");
        if (accept != null && accept.indexOf("application/json") != -1) {
            return true;
        }
        String xRequestedWith = request.getHeader("X-Requested-With");
        if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) {
            return true;
        }
        String uri = request.getRequestURI();
        if (StrUtil.containsAnyIgnoreCase(uri, ".json", ".xml")) {
            return true;
        }
        String ajax = request.getParameter("__ajax");
        if (StrUtil.containsAnyIgnoreCase(uri, ".json", ".xml")) {
            return true;
        }
        return false;
    }

    //工具类 spring中提供的路径匹配器
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    /**
     * 判断请求是否需要放行
     *
     * @param path       所有需要放行的路径
     * @param requestUri 当前请求的路径
     * @return
     */
    private boolean check(String[] path, String requestUri) {
        for (int i = 0; i < path.length; i++) {
            if (PATH_MATCHER.match(path[i], requestUri)) {
                return true;
            }
        }
        return false;
    }
}
